#include <QApplication>
#include <QPainter>
#include <QToolBar>
#include <QMenu>
#include <QToolButton>
#include <QFileDialog>
#include <QTranslator>
#include <QFile>
#include "common.h"
#include "config.h"
#include "centerwindow.h"
#include "view/preferencedialog.h"
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QFile cssfile(CSS_FILE);
    if (cssfile.open(QIODevice::ReadOnly | QIODevice::Text)){
        QByteArray ba = cssfile.readAll();
        cssfile.close();
        QString css(ba);
        qApp->setStyleSheet(css);
    }

    m_background.load(IMG_DIR+"bkground.png");
    m_config = Config::instance();

    m_translator = new QTranslator(this);
    updateTranslator();
    qApp->installTranslator(m_translator);

    setWindowTitle(tr("media convertor"));

    createActions();
    createToolBars();

    m_centerFrame = new CenterWindow(this);
    setCentralWidget(m_centerFrame);
    connect(this, SIGNAL(signalLanguageChanged()), m_centerFrame, SIGNAL(signalLanguageChanged()));
    connect(m_centerFrame, SIGNAL(signalFileSelectionChanged(bool,bool)), this, SLOT(slotFileSelectionChanged(bool,bool)));
}

MainWindow::~MainWindow()
{

}

void MainWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.drawPixmap(0,0,width(),height(),m_background);
}

void MainWindow::updateToolBarLanguage()
{
    m_addFileButton->setToolTip(tr("Add file..."));
    m_addFileButton->setStatusTip(tr("Add media files"));

    m_addDirButton->setToolTip(tr("Add dir..."));
    m_addDirButton->setStatusTip(tr("Add media directory"));

    m_selectAllButton->setToolTip(tr("Select all"));
    m_selectAllButton->setStatusTip(tr("select all files"));

    m_delSelectedButton->setToolTip(tr("Delete selected"));
    m_delSelectedButton->setStatusTip(tr("delete selected files"));

    m_changeLanguageButton->setToolTip(tr("Change language"));
    m_changeLanguageButton->setStatusTip(tr("change the language"));

    m_preferenceButton->setToolTip(tr("Preferences..."));
    m_preferenceButton->setStatusTip(tr("change the preferences"));

    m_systemHelpButton->setToolTip(tr("Select all"));
    m_systemHelpButton->setStatusTip(tr("help information"));

    m_helpHelpAct->setText(tr("Help"));
    m_helpBuyAct->setText(tr("Buy"));
    m_helpRegisterAct->setText(tr("Enter License Code"));
    m_helpFeedbackAct->setText(tr("Feedback and Support"));
    m_helpUpdateAct->setText(tr("Check Update"));
    m_helpAboutAct->setText(tr("About"));
}

void MainWindow::createActions()
{
    // add file button
    m_addFileButton = createToolButton("btn_add_file.png",
                                       "btn_add_file_h.png",
                                       "btn_add_file_d.png",
                                       tr("Add file..."),
                                       tr("Add media files"),
                                       QKeySequence::Open);
    connect( m_addFileButton, SIGNAL(clicked()), this, SLOT(slotAddFiles()));
    // add dir button
    m_addDirButton = createToolButton("btn_add_dir.png",
                                       "btn_add_dir_h.png",
                                       "btn_add_dir_d.png",
                                       tr("Add dir..."),
                                       tr("Add media directory"));
    connect( m_addDirButton, SIGNAL(clicked()), this, SLOT(slotAddDir()));
    // select all button
    m_selectAllButton = createToolButton("btn_select_all.png",
                                       "btn_select_all_h.png",
                                       "btn_select_all_d.png",
                                       tr("Select all"),
                                       tr("select all files"));
    connect( m_selectAllButton, SIGNAL(clicked()), this, SLOT(slotSelectAll()));
    // delete selected button
    m_delSelectedButton = createToolButton("btn_del.png",
                                       "btn_del_h.png",
                                       "btn_del_d.png",
                                       tr("Delete selected"),
                                       tr("delete selected files"));
    connect( m_delSelectedButton, SIGNAL(clicked()), this, SLOT(slotDeleteSelected()));
    m_delSelectedButton->setEnabled(false);

    // change language button
    m_changeLanguageButton = createToolButton("btn_lang.png",
                                       "btn_lang_h.png",
                                       "btn_lang_d.png",
                                       tr("Change language"),
                                       tr("change the language"));
    connect( m_changeLanguageButton, SIGNAL(clicked()), this, SLOT(slotShowLanguageMenu()));
    // language menu
    m_languageMenu = new QMenu(this);
    QStringList lanList = Config::lanList();
    QAction *lanAction;
    m_lanActList.clear();
    for (int i = 0; i < Config::LAN_COUNT; ++i) {
        lanAction = m_languageMenu->addAction(lanList[i]);
        lanAction->setCheckable(true);
        if (i==m_config->getIntValue(Config::SYS_LANGUAGE)){
            lanAction->setChecked(true);
        }else{
            lanAction->setChecked(false);
        }
        m_lanActList << lanAction;
    }
    connect(m_languageMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotLanMenuClicked(QAction*)));
    // change preference button
    m_preferenceButton = createToolButton("btn_preference.png",
                                       "btn_preference_h.png",
                                       "btn_preference_d.png",
                                       tr("Preferences..."),
                                       tr("change the preferences"));
    connect( m_preferenceButton, SIGNAL(clicked()), this, SLOT(slotChangePreferences()));
    // help button
    m_systemHelpButton = createToolButton("btn_help.png",
                                          "btn_help_h.png",
                                          "btn_help_d.png",
                                          tr("Select all"),
                                          tr("help information"));
    connect( m_systemHelpButton, SIGNAL(clicked()), this, SLOT(slotShowSystemHelpMenu()));
    m_systemHelpMenu = new QMenu(this);
    // help menu
    m_helpHelpAct = m_systemHelpMenu->addAction(tr("Help"));
    m_helpBuyAct = m_systemHelpMenu->addAction(tr("Buy"));
    m_helpRegisterAct = m_systemHelpMenu->addAction(tr("Enter License Code"));
    m_helpFeedbackAct = m_systemHelpMenu->addAction(tr("Feedback and Support"));
    m_helpUpdateAct = m_systemHelpMenu->addAction(tr("Check Update"));
    m_helpAboutAct = m_systemHelpMenu->addAction(tr("About"));
    m_systemHelpMenu->insertSeparator(m_helpAboutAct);
    m_systemHelpMenu->insertSeparator(m_helpBuyAct);
    m_systemHelpMenu->insertSeparator(m_helpUpdateAct);
    connect(m_helpHelpAct, SIGNAL(triggered()), this, SLOT(slotHelpHelp()));
    connect(m_helpBuyAct, SIGNAL(triggered()), this, SLOT(slotHelpBuy()));
    connect(m_helpRegisterAct, SIGNAL(triggered()), this, SLOT(slotHelpRegister()));
    connect(m_helpFeedbackAct, SIGNAL(triggered()), this, SLOT(slotHelpFeedback()));
    connect(m_helpUpdateAct, SIGNAL(triggered()), this, SLOT(slotHelpUpdate()));
    connect(m_helpAboutAct, SIGNAL(triggered()), this, SLOT(slotHelpAbout()));
}

QToolButton *MainWindow::createToolButton(const QString&normalBg, const QString&highlightBg, const QString&disabledBg,
                                          const QString&toolTip, const QString&statusTip, QKeySequence::StandardKey key)
{
    QToolButton *toolButton = new QToolButton(this);
    toolButton->setFocusPolicy(Qt::NoFocus);
    toolButton->setStyleSheet("QToolButton{background-image:url("+IMG_DIR+normalBg+");}"
                                "QToolButton{background-repeat:no-repeat; background-position: center center;}"
                                "QToolButton{border:none; color:rgb(118,0,97);}"
                                "QToolButton:hover{background-image: url("+IMG_DIR+highlightBg+");}"
                                "QToolButton:disabled{background-image: url("+IMG_DIR+disabledBg+");};"
                                "QToolButton:pressed{background-image: url("+IMG_DIR+highlightBg+");};");
    toolButton->setToolTip(toolTip);
    toolButton->setStatusTip(statusTip);
    toolButton->setShortcut(key);
    return toolButton;
}

void MainWindow::createToolBars()
{
    m_mainToolBar = addToolBar(tr("main"));
    m_mainToolBar->setFloatable(false);
    m_mainToolBar->setMovable(false);
    m_mainToolBar->setAttribute(Qt::WA_NoMousePropagation);
    m_mainToolBar->setIconSize(QSize(55,55));
    m_mainToolBar->addWidget(m_addFileButton);
    m_mainToolBar->addWidget(m_addDirButton);
    m_mainToolBar->addWidget(m_selectAllButton);
    m_mainToolBar->addWidget(m_delSelectedButton);
    m_mainToolBar->addWidget(m_changeLanguageButton);
    m_mainToolBar->addWidget(m_preferenceButton);
    m_mainToolBar->addWidget(m_systemHelpButton);
}

void MainWindow::slotAddFiles()
{
    QFileDialog::Options options;
    QString selectedFilter;
    QStringList files = QFileDialog::getOpenFileNames(
                                this, tr("Select one or more files"),
                                openFilesPath,
                                tr("All Files (*);;Text Files (*.txt)"),
                                &selectedFilter,
                                options);
    if (files.count()) {
        m_centerFrame->addFileList(files);
    }
}

void MainWindow::slotAddDir()
{
    QFileDialog::Options options = QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly;
    QString directory = QFileDialog::getExistingDirectory(this,
                                "",
                                "directoryLabel->text()",
                                options);
    if (!directory.isEmpty()){
        m_centerFrame->addDirectory(directory);
    }
}

void MainWindow::slotSelectAll()
{

}

void MainWindow::slotDeleteSelected()
{
    m_centerFrame->deleteSelectedFiles();
}

void MainWindow::slotShowLanguageMenu()
{
    QRect rect = m_changeLanguageButton->geometry();
    QPoint pt = QPoint(rect.x()+3, rect.y()+rect.height()-2);
    pt = this->mapToGlobal(pt);
    m_languageMenu->popup(pt);
}

void MainWindow::slotLanMenuClicked(QAction *lanAct)
{
    int actCount = m_lanActList.count();
    int curSelected = 0;
    for(int i=0; i<actCount; i++){
        if (m_lanActList[i]==lanAct){
            m_lanActList[i]->setChecked(true);
            curSelected = i;
        }else{
            m_lanActList[i]->setChecked(false);
        }
    }
    if (curSelected!=m_config->getIntValue(Config::SYS_LANGUAGE)){
        slotLanguageChanged(curSelected);
    }
}

void  MainWindow::slotLanguageChanged(int curLan)
{
    m_config->setIntValue(Config::SYS_LANGUAGE, curLan);
    updateTranslator();
    updateUiLanguage();
    emit signalLanguageChanged();
}

void MainWindow::slotFileSelectionChanged(bool hasFile,bool hasSelection)
{
    if (hasFile){
        m_delSelectedButton->setEnabled(hasSelection);
    }else{
        m_delSelectedButton->setEnabled(false);
    }
}

void MainWindow::updateTranslator()
{
    int curLan = m_config->getIntValue(Config::SYS_LANGUAGE);
    DBUG() << curLan << QLocale::system().name();
    switch (curLan)
    {
    case Config::LAN_EN:
        m_translator->load(LAN_DIR + "lans/lan_en");
        break;
    case Config::LAN_CN:
        m_translator->load(LAN_DIR + "lans/lan_zh_CN");
        break;
    default:
        ERRR() << "wrong language" << curLan;
        break;
    }
}

void MainWindow::updateUiLanguage()
{
    // title
    setWindowTitle(tr("media convertor"));
    // toolbar
    updateToolBarLanguage();
}

void MainWindow::slotChangePreferences()
{
    PreferenceDialog pd(this);
    pd.exec();
}

void MainWindow::slotShowSystemHelpMenu()
{
    QRect rect = m_systemHelpButton->geometry();
    QPoint pt = QPoint(rect.x()+3, rect.y()+rect.height()-2);
    pt = this->mapToGlobal(pt);
    m_systemHelpMenu->popup(pt);
}

void MainWindow::slotHelpHelp()
{

}

void MainWindow::slotHelpBuy()
{

}

void MainWindow::slotHelpRegister()
{

}

void MainWindow::slotHelpFeedback()
{

}

void MainWindow::slotHelpUpdate()
{

}

void MainWindow::slotHelpAbout()
{

}
